package backed.interceptor;

import backed.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT Token拦截器
 * 用于验证请求中的JWT Token是否有效，并将用户信息存储到请求上下文中
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是OPTIONS请求（CORS预检请求），直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 从请求头中获取token
        String authHeader = request.getHeader("Authorization");
        
        // 如果没有Authorization头，返回401
        if (authHeader == null || authHeader.isEmpty()) {
            sendUnauthorizedResponse(response, "缺少认证信息");
            return false;
        }

        // 提取token（格式：Bearer <token>）
        String token = null;
        if (authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else {
            sendUnauthorizedResponse(response, "Token格式错误，请使用Bearer格式");
            return false;
        }

        // 验证token是否有效
        if (!jwtUtils.validateToken(token)) {
            // 检查是否是过期（用于更详细的错误提示）
            String errorMessage = jwtUtils.isTokenExpired(token) 
                ? "Token已过期，请重新登录" 
                : "Token无效";
            sendUnauthorizedResponse(response, errorMessage);
            return false;
        }

        // 从token中获取用户ID并存储到请求属性中，方便后续使用
        Long userId = jwtUtils.getUserIdFromToken(token);
        if (userId != null) {
            request.setAttribute("userId", userId);
            request.setAttribute("token", token);
        }

        // Token有效，放行
        return true;
    }

    /**
     * 发送401未授权响应
     */
    private void sendUnauthorizedResponse(HttpServletResponse response, String message) throws Exception {
        // 设置CORS响应头，确保前端能接收到401状态码
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", message);
        result.put("code", 401);
        
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }
}

